<template>
    <div class="closure-add-container">
        <el-page-header content="结案处理" @back="handleBack" class="page-header" />

        <el-card class="main-card" shadow="hover">
            <!-- 基础信息（来自报案） -->
            <el-descriptions :column="2" border class="mb-16">
                <el-descriptions-item label="报案号">{{ form.reportNo }}</el-descriptions-item>
                <el-descriptions-item label="保单号">{{ form.policyId }}</el-descriptions-item>
                <el-descriptions-item label="投保人ID">{{ form.insuredId }}</el-descriptions-item>
                <el-descriptions-item label="灾祸类型">{{ disasterName }}</el-descriptions-item>
            </el-descriptions>

            <!-- 结案表单 -->
            <el-form ref="formRef" :model="form" :rules="rules" label-width="150px">
                <el-row :gutter="16">
                    <el-col :span="8">
                        <el-form-item label="核赔ID" prop="verificationId">
                            <el-input v-model="form.verificationId" placeholder="查询中..." readonly />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="结案类型" prop="closureType">
                            <el-select v-model="form.closureType" placeholder="请选择结案类型" style="width:100%">
                                <el-option label="正常赔付结案" :value="1" />
                                <el-option label="拒赔结案" :value="2" />
                                <el-option label="部分赔付结案" :value="3" />
                                <el-option label="预赔抵扣后结案" :value="4" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="结案员" prop="closerId">
                            <el-select v-model="form.closerId" placeholder="请选择结案员" style="width:100%">
                                <el-option v-for="item in closerList" :key="item.workNo"
                                    :label="`${item.realName} (${item.workNo})`" :value="item.workNo">
                                    <div>{{ item.realName }}({{ item.workNo }})</div>
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="16">
                    <el-col :span="8">
                        <el-form-item label="已预赔(元)" prop="preClaimAmount">
                            <el-input v-model="form.preClaimAmount" readonly placeholder="查询中..." />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="最终赔付(元)" prop="finalPayAmount">
                            <el-input v-model="form.finalPayAmount" readonly />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="实际支付(元)">
                            <el-input :model-value="actualPayAmountText" readonly />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="损失概况" prop="lossSummary">
                    <el-input v-model="form.lossSummary" type="textarea" :rows="3"
                        placeholder="汇总报案、查勘、立案信息，简要描述损失概况" />
                </el-form-item>

                <el-form-item label="结案意见" prop="closureOpinion">
                    <el-input v-model="form.closureOpinion" type="textarea" :rows="3"
                        placeholder="如：流程合规，已完成支付，同意结案 / 不属于保险责任，同意拒赔结案" />
                </el-form-item>

                <el-row :gutter="16">
                    <el-col :span="12">
                        <el-form-item label="是否已通知农户" prop="noticeStatus">
                            <el-switch v-model="form.noticeStatus" :active-value="1" :inactive-value="0" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" v-if="form.noticeStatus === 1">
                        <el-form-item label="通知时间" prop="noticeTime">
                            <el-date-picker v-model="form.noticeTime" type="datetime" style="width:100%"
                                format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DDTHH:mm:ss" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="农户反馈">
                    <el-input v-model="form.farmerFeedback" type="textarea" :rows="2" placeholder="如：认可赔付结果，无异议" />
                </el-form-item>
                <div class="actions">
                    <el-button @click="handleBack">取消</el-button>
                    <el-button type="primary" :loading="submitting" @click="handleSubmit">提交结案</el-button>
                </div>
            </el-form>
        </el-card>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import hxxp from '@/utils/hxxp'

const route = useRoute()
const router = useRouter()

const formRef = ref()
const submitting = ref(false)
const verificationLoading = ref(false)
const verificationList = ref([])
const closerList = ref([])

const form = reactive({
    // 由后端生成：closureId
    reportNo: route.query.reportNo || '',
    verificationId: '',
    policyId: route.query.policyId || '',
    insuredId: route.query.insuredId || '',
    disasterType: route.query.disasterType || '',
    lossSummary: route.query.lossDescription || '',
    closureType: undefined,
    preClaimAmount: '0.00',
    finalPayAmount: '0.00',
    actualPayAmount: 0,
    closerId: '', // 
    closureTime: '', // 由后端填充，前端不传也可
    closureOpinion: '',
    noticeStatus: 0,
    noticeTime: '',
    farmerFeedback: '',
    caseArchiveUrl: ''
})

const rules = {
    reportNo: [{ required: true, message: '报案号缺失', trigger: 'blur' }],
    verificationId: [{ required: true, message: '请选择核赔ID', trigger: 'change' }],
    policyId: [{ required: true, message: '保单号缺失', trigger: 'blur' }],
    insuredId: [{ required: true, message: '投保人ID缺失', trigger: 'blur' }],
    closureType: [{ required: true, message: '请选择结案类型', trigger: 'change' }],
    closerId: [{ required: true, message: '请选择结案员', trigger: 'change' }],
    finalPayAmount: [
        { required: true, message: '最终赔付金额缺失', trigger: 'blur' }
    ],
    preClaimAmount: [
        {
            validator: (_, v, cb) => {
                const n = Number(v)
                if (isNaN(n) || n < 0) return cb(new Error('金额需为非负数'))
                cb()
            }, trigger: 'blur'
        }
    ],
    lossSummary: [{ required: true, message: '请填写损失概况', trigger: 'blur' }],
    closureOpinion: [{ required: true, message: '请填写结案意见', trigger: 'blur' }],
    noticeTime: [{
        validator: (_, v, cb) => {
            if (form.noticeStatus === 1 && !v) return cb(new Error('请选择通知时间'))
            cb()
        }, trigger: 'change'
    }]
}

const disasterMap = { '1': '暴雨', '2': '洪水', '3': '病虫害', '4': '疫病', '5': '其他' }
const disasterName = computed(() => disasterMap[String(form.disasterType)] || '未知')

const actualPayAmount = computed(() => {
    const finalAmt = Number(form.finalPayAmount || 0)
    const preAmt = Number(form.preClaimAmount || 0)
    return Math.max(0, finalAmt - preAmt)
})
const actualPayAmountText = computed(() => actualPayAmount.value.toFixed(2))

// 查询核赔信息
const fetchVerificationList = async () => {
    if (!form.reportNo) return

    verificationLoading.value = true
    try {
        const res = await hxxp.get('/aiClaimVerification/all', {
            params: {
                reportNo: form.reportNo,
            }
        })
        if (res.code === 100200 && res.data && res.data.list && res.data.list.length > 0) {
            // 取第一个核赔记录，直接填充到表单中
            const verification = res.data.list[0]
            form.verificationId = verification.verificationId
            form.finalPayAmount = (verification.finalPayAmount || 0).toFixed(2)
            verificationList.value = res.data.list
        } else {
            verificationList.value = []
            form.verificationId = ''
            form.finalPayAmount = '0.00'
            ElMessage.warning('未找到相关核赔信息')
        }
    } catch (e) {
        console.error('查询核赔信息失败:', e)
        verificationList.value = []
        form.verificationId = ''
        form.finalPayAmount = '0.00'
        ElMessage.error('查询核赔信息失败')
    } finally {
        verificationLoading.value = false
    }
}

// 查询结案员列表
const fetchCloserList = async () => {
    try {

        const res = await hxxp.get('/aiStaffUser/worker', {
            params: {
                positionCode: 'PTN008',
            }
        })
        if (res.code === 100200) {
            closerList.value = res.data
        }
    } catch (e) {
        console.error('查询结案员列表失败:', e)
    }
}

// 查询预赔金额
const fetchPreClaimAmount = async () => {
    if (!form.reportNo) return

    try {
        const res = await hxxp.get('/aiPreClaim/list', {
            params: {
                reportId: form.reportNo,
                pageNum: 1,
                pageSize: 100 // 获取所有预赔记录
            }
        })

        if (res.code === 100200 && res.data && res.data.list) {
            // 计算总的已预赔金额（所有审核通过的预赔金额之和）
            let totalPreClaimAmount = 0
            res.data.list.forEach(item => {
                // 只统计审核通过（reviewResult=1）和部分通过（reviewResult=2）的预赔金额
                if ((item.reviewResult === 1 || item.reviewResult === 2) && item.approvedAmount) {
                    totalPreClaimAmount += Number(item.approvedAmount) || 0
                }
            })

            form.preClaimAmount = totalPreClaimAmount.toFixed(2)
            console.log('查询到预赔金额:', totalPreClaimAmount)
        } else {
            form.preClaimAmount = '0.00'
            console.log('未找到预赔记录')
        }
    } catch (e) {
        console.error('查询预赔金额失败:', e)
        form.preClaimAmount = '0.00'
        ElMessage.error('查询预赔金额失败')
    }
}


onMounted(async () => {

    // 查询核赔信息、结案员列表和预赔金额
    await Promise.all([
        fetchVerificationList(),
        fetchCloserList(),
        fetchPreClaimAmount()
    ])
})

const handleSubmit = async () => {
    if (!formRef.value) return
    try {
        await formRef.value.validate()
    } catch (e) {
        return
    }
    submitting.value = true
    try {
        const payload = {
            ...form,
            actualPayAmount: actualPayAmount.value,
        }
        const res = await hxxp.post('/aiClaimClosure', payload)
        if (res.code === 100200) {
            ElMessage.success('新增结案成功')
            router.push('/closureList')
        } else {
            ElMessage.error(res.msg || '新增结案失败')
        }
    } catch (e) {
        console.error(e)
        ElMessage.error('提交失败，请稍后重试')
    } finally {
        submitting.value = false
    }
}

const handleBack = () => router.back()
</script>

<style scoped>
.closure-add-container {
    padding: 20px;
    max-width: 1100px;
    margin: 0 auto;
}

.page-header {
    margin-bottom: 16px;
}

.mb-16 {
    margin-bottom: 16px;
}

.main-card {
    padding: 16px;
}

.actions {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 12px;
}
</style>
